#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <pthread.h>

namespace lcl
{
    using func_t = std::function<void *(void *)>;
    
    class Thread
    {
    //public:
        // using func_t = std::function<void *(void *)>;

    public:
        Thread()
        {
            char namebuffer[1024];
            snprintf(namebuffer, sizeof namebuffer, "thread->%d", threadnum++);
            _name = namebuffer;
        }

        void start(func_t func, void *args = nullptr)
        {
            _func = func;
            _args = args;
            // 创建线程
            int n = pthread_create(&_tid, nullptr, start_routine, this);
            if (n != 0)
                std::cout << "pthread_create error" << std::endl;
        }

        // 这里必须是静态的，因为类内含有this指针，不是静态的相当于有两个参数，但是这里只要一个。
        static void *start_routine(void *args)
        {
            Thread *_this = static_cast<Thread *>(args);
            return _this->callback();
        }

        void *callback()
        {
            _func(_args);
        }

        void join()
        {
            int n = pthread_join(_tid, nullptr);
            if (n != 0)
                std::cout << "pthread_join error" << std::endl;
        }

        std::string threadname()
        {
            return _name;
        }

        ~Thread()
        {
        }

    private:
        std::string _name;
        func_t _func;
        void *_args;
        pthread_t _tid;

        static int threadnum; // 静态变量，类内声明，类外定义
    };
    int Thread::threadnum = 1;
} // end namespace lcl
